package controller

import (
	"http_server/src/common_util"
	"http_server/src/models"
	"http_server/src/services"
	"http_server/src/utils"
	"io"
	"mime/multipart"
	"net/http"

	"github.com/gin-gonic/gin"
)

type UserController struct {
	userService services.UserService
}

func NewUserController(userService services.UserService) *UserController {
	return &UserController{
		userService: userService,
	}
}

// Login 处理登录请求
func (uc *UserController) Login(c *gin.Context) {
	var req models.LoginRequest

	if err := c.ShouldBindJSON(&req); err != nil {
		utils.RespondWithJSON(c, http.StatusBadRequest, "请求参数有误", nil)
		return
	}
	response, err := uc.userService.Login(c, req)
	if err != nil {
		common_util.ErrorLogger.Printf(err.Error())
		utils.RespondWithJSON(c, http.StatusInternalServerError, "服务器内部错误", nil)
		return
	}
	utils.RespondWithJSON(c, response.Code, response.Message, response.Data)
}

func (uc *UserController) GetUserMessage(c *gin.Context) {
	username := c.Param("username")
	user, err := uc.userService.GetUserMessage(username)
	if err != nil {
		common_util.ErrorLogger.Printf(err.Error())
		utils.RespondWithJSON(c, http.StatusInternalServerError, "服务器内部错误", nil)
		return
	}

	utils.RespondWithJSON(c, 200, "success", user)
}

func (uc *UserController) UpdateUserMessage(c *gin.Context) {
	// 获取表单数据并验证
	username := c.PostForm("username")
	nickname := c.PostForm("nickname")
	// 处理文件上传
	file, err := c.FormFile("picture")
	if err != nil {
		errMessage := "服务器内部错误"
		if err.Error() == "request Content-Type isn't multipart/form-data" {
			errMessage = "请求中表单缺少图片文件参数"
		}
		utils.RespondWithJSON(c, http.StatusInternalServerError, errMessage, nil)
		common_util.ErrorLogger.Printf("获取请求中的图片文件出现错误：%v", err.Error())
		return
	}
	// 读取文件内容
	fileBytes, err := file.Open()
	if err != nil {
		utils.RespondWithJSON(c, http.StatusInternalServerError, "服务器内部错误", nil)
		common_util.ErrorLogger.Printf("读取请求图片文件内容出现错误：%v", err)
		return
	}
	defer func(fileBytes multipart.File) {
		err := fileBytes.Close()
		if err != nil {
			common_util.ErrorLogger.Printf("关闭打开的图片文件内容出现错误：%v", err)
		}
	}(fileBytes)
	// 将文件内容读取到字节切片中
	fileData, err := io.ReadAll(fileBytes)
	if err != nil {
		utils.RespondWithJSON(c, http.StatusInternalServerError, "服务器内部错误", nil)
		common_util.ErrorLogger.Printf("读取请求图片文件内容数据存储到字节数组中出现错误：%v", err)
		return
	}

	resp, err := uc.userService.UpdateUserMessage(username, nickname, fileData)
	if err != nil {
		common_util.ErrorLogger.Printf(err.Error())
		utils.RespondWithJSON(c, http.StatusInternalServerError, "服务器内部错误", nil)
		return
	}
	utils.RespondWithJSON(c, resp.Code, resp.Message, nil)
}
